import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置中文字体为黑体
plt.rcParams['axes.unicode_minus'] = False   # 解决负号显示问题

# 原始数据
data = np.array([
    [50, 50, 9],
    [28, 9, 4],
    [17, 15, 3],
    [25, 40, 5],
    [28, 40, 2],
    [50, 50, 1],
    [50, 50, 9],
    [50, 40, 9],
    [40, 40, 5],
    [50, 50, 9],
    [50, 50, 9],
    [50, 50, 9],
    [40, 40, 9],
    [40, 32, 17],
    [40, 32, 17]
])

# 初始化KMeans算法，设k = 3
kmeans = KMeans(n_clusters=3, random_state=0)

# 拟合数据
kmeans.fit(data)

# 预测中国男足（第一行数据）所属的簇
china_result = kmeans.predict(data[0].reshape(1, -1))

# 输出中国男足所属的簇
print("中国男足所属的簇:", china_result[0])

# 获取聚类中心
centroids = kmeans.cluster_centers_
print("聚类中心:")
for i, centroid in enumerate(centroids):
    print(f"簇{i + 1}: {centroid}")

# 获取每个数据点所属的簇
labels = kmeans.labels_
print("各球队所属的簇:")
for i, label in enumerate(labels):
    print(f"球队{i + 1}: 簇{label + 1}")

# 可视化
plt.scatter(data[:, 0], data[:, 1], c=labels)
plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=200, linewidths=3, color='r')
plt.xlabel("2006年世界杯成绩")
plt.ylabel("2010年世界杯成绩")
plt.title("亚洲足球队聚类结果")
plt.show()